package errorx

import "net/http"

type CodeError struct {
	HttpCode int
	Code     int         `json:"code"`
	Message  string      `json:"message"`
	Content  interface{} `json:"data,omitempty"`
}

type CodeErrorResponse struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

func codeError(httpCode, code int, msg ...string) error {
	var m string
	if len(msg) > 0 {
		m = msg[0]
	} else {
		m = text(code)
	}
	return &CodeError{HttpCode: httpCode, Code: code, Message: m}
}

func NewDefaultError() error {
	return codeError(http.StatusOK, ErrorDefault)
}

func NewLogicError(code int) error {
	return codeError(http.StatusOK, code)
}

func NewBadRequestError(msg ...string) error {

	return codeError(http.StatusBadRequest, ErrorDefaultBadRequest, msg...)
}

func NewBadRequestWithData(code int, data interface{}) error {

	return &CodeError{HttpCode: http.StatusBadRequest, Code: code, Message: text(code), Content: data}
}

func NewTooManyRequestError(msg ...string) error {

	return codeError(http.StatusTooManyRequests, ErrorDefaultBadRequest, msg...)
}

func NewForbiddenError(msg ...string) error {
	return codeError(http.StatusForbidden, ErrorDefaultForbidden, msg...)
}

func NewUnauthorizedError(msg ...string) error {
	return codeError(http.StatusUnauthorized, ErrorDefaultUnanthorized, msg...)
}

func NewNotFoundError(msg ...string) error {
	return codeError(http.StatusNotFound, ErrorDefaultNotFound, msg...)
}

func NewInternetError(msg ...string) error {
	return codeError(http.StatusInternalServerError, ErrorInternet, msg...)
}

func (e *CodeError) Error() string {
	return e.Message
}

func (e *CodeError) Data() *CodeErrorResponse {
	return &CodeErrorResponse{
		Code:    e.Code,
		Message: e.Message,
		Data:    e.Content,
	}
}
